
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#include "SHT40.h"
#include "WIFI_SMARTCONFIG.h"
#include "mqtt_aliot.h"
#include "ctrl_data.h"
#include "esp_log.h"
#include "data2nvs.h"
#include "esp_err.h"
#include "voltage.h"
#include "light_sleep.h"
#include "deep_sleep.h"
#include "driver/rtc_io.h"

#define MAIN_TAG "MAIN"
bool is_first_boot = true;
RTC_DATA_ATTR bool rtc_wakeup_flag = false;
 esp_err_t err = NULL ;
void app_main(void) {
    // 判断是否是从深度睡眠唤醒
    if (rtc_wakeup_flag) {
        is_first_boot = false;
        ESP_LOGI(MAIN_TAG, "Woken up from deep sleep, executing wakeup logic.");
        // 执行唤醒后的逻辑
        // 这里不再需要调用 Deep_Sleep_WakeUp()
        rtc_wakeup_flag = false;  // 重置唤醒标志
    } else {
        is_first_boot = true;
        ESP_LOGI(MAIN_TAG, "First boot, executing initial setup.");
        // 第一次启动时执行初始化操作
        err = data2nvs_init();  // 初始化 NVS 存储
        if (err != ESP_OK) {
            ESP_LOGE(MAIN_TAG, "data2nvs init fail");
            return;
        }
    }

        wifi_init();  // 初始化 Wi-Fi
        wifi_smart_normal_config(is_first_boot);  // 根据是否第一次启动来进行 Wi-Fi 配网

        SHT40_init();  // 初始化 SHT40 传感器

        aliot_start();  // 启动阿里云 IoT
        ESP_LOGI(MAIN_TAG, "Aliot start success");

        // 创建任务
        xTaskCreatePinnedToCore(mqtt_read_data, "mqtt_read_data", 4096, NULL, 2, NULL, 1);
        xTaskCreatePinnedToCore(voltage_init, "voltage_init", 4096, NULL, 2, NULL, 1);

        vTaskDelay(pdMS_TO_TICKS(10000));

        deep_sleep();  // 进入深度睡眠
 

    while (1) {
        vTaskDelay(pdMS_TO_TICKS(2000));
    }
}
